package com.deep.sftp;


import com.jcraft.jsch.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Properties;

/**
 * @author: chenly
 * @date: 2022-11-01 11:02
 * @description:
 * @version: 1.0
 */
@Component
@Data
@Slf4j
public class SftpClientObject {

    private ChannelSftp sftp;

    public SftpClientObject(SftpProperties sftpProperties) throws Exception{
        connect(sftpProperties);
    }
    /**
     * 连接登陆远程服务器
     */
    public ChannelSftp connect(SftpProperties sftpProperties) throws Exception  {
        JSch jSch = new JSch();
        Session session = null;
        session = jSch.getSession(sftpProperties.getUsername(), sftpProperties.getHost(), sftpProperties.getPort());
        session.setPassword(sftpProperties.getPassword());
        session.setConfig(this.getSshConfig());
        session.connect();
        sftp = (ChannelSftp)session.openChannel("sftp");
        sftp.connect();
        return sftp;
    }

    /**
     * 服务配置
     * @return
     */
    private Properties getSshConfig() {
        Properties sshConfig =  new Properties();
        sshConfig.put("StrictHostKeyChecking", "no");
        return sshConfig;
    }

    /**
     * 关闭连接
     */
    public void disconnect() {
        try {
            if(sftp!=null){
                if(sftp.getSession().isConnected()){
                    sftp.getSession().disconnect();
                }
                sftp.disconnect();
            }

        } catch (Exception e) {
            log.error("关闭与sftp服务器会话连接异常",e);
        }
    }

    //验证连接
    public boolean validateConnect() {
        try {
            if(sftp == null){
                return false;
            }
            return sftp.getSession().isConnected() && sftp.isConnected();
        } catch (Exception e) {
            return false;
        }
    }

    public ChannelSftp getSftp() {
        return sftp;
    }

    public void setSftp(ChannelSftp sftp) {
        this.sftp = sftp;
    }
}